#!/usr/bin/env python
#-*- coding: utf-8 -*-
from fx.models.user import AdminUser
from fx.constants.misc import DEFAULT_PASSWORD
from fx.constants.misc import ADMIN_PAGE_SIZE


def save_admin_user(username, mobile_num, company, name, role, user=None):
    if not user:
        user = AdminUser(password=DEFAULT_PASSWORD)
    user.username = username
    user.mobile_num = mobile_num
    user.company = company
    user.name = name
    user.role = role
    user.save()
    return user


def get_admin_user_by_mobile(mobile_num):
    return AdminUser.query.filter_by(mobile_num=mobile_num).first() or None


def get_admin_user_by_username(username):
    return AdminUser.query.filter_by(username=username).first() or None


def get_admin_user_by_company(company):
    return AdminUser.query.filter_by(company=company).first() or None


def get_admin_user_by_id(u_id):
    return AdminUser.query.get(u_id)


def get_admin_user_by_page(is_active=None, role=None, page=1, pagesize=ADMIN_PAGE_SIZE):

    query_kwargs = dict()
    if is_active is not None:
        query_kwargs['is_active'] = is_active
    if role is not None:
        query_kwargs['role'] = role
    query = AdminUser.query.filter_by(**query_kwargs)
    users = query.order_by(
        AdminUser.created.desc()
    ).paginate(page, pagesize)
    items = users.items
    return items, users.total








